﻿using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

namespace FlyingHat.Common.Helper.Image
{
    public static class ImageSharpExtension
    {
        public static IImageProcessingContext DrawGridLines(this IImageProcessingContext source, int count, Color color,
            int imageWidth, int imageHeight, Random imageRandom)
        {
            // 二维坐标点
            var points = new List<PointF> { new PointF(0, 0) };
            for (int i = 0; i < count; i++)
            {
                // 随机坐标点
                points.Add(new PointF(imageRandom.Next(0, imageWidth), imageRandom.Next(0, imageHeight)));
            }
            points.Add(new PointF(imageWidth, imageHeight));
            // 绘制线
            source = source.DrawLines(color, 1, points.ToArray());
            return source;
        }

        public static IImageProcessingContext DrawGridText(this IImageProcessingContext source, string text, int imageWidth, int imageHeight,
            List<Font> fonts, string[] colorHex, Random imageRandom)
        {
            // 图片宽度除以文字长度等于每个字所占的宽度
            var textWidth = imageWidth / text.Length;
            // 取文字的宽度和图片的高度最小的一个，保证文字不越界
            var imgSize = Math.Min(textWidth, imageHeight);
            //设置字体的大小，最大是文字的尺寸
            var fontMiniSize = (int)(imgSize * 0.8);
            var fontMaxSize = imgSize;
            // 字体的样式 正常、粗体、斜体、粗斜体
            var fontStyle = new FontStyle[] { FontStyle.Regular, FontStyle.Bold, FontStyle.Italic, FontStyle.BoldItalic };
            // 循环每个字
            for (int i = 0; i < text.Length; i++)
            {
                using var img = new Image<Rgba32>(imgSize, imgSize);
                // 随机字体
                var font = new Font(fonts[imageRandom.Next(0, fonts.Count)], imageRandom.Next(fontMiniSize, fontMaxSize), fontStyle[imageRandom.Next(fontStyle.Length)]);
                // 随机颜色
                var color = Color.ParseHex(colorHex[imageRandom.Next(0, colorHex.Length)]);
                img.Mutate(x => x
                            // 绘制文字
                            .DrawText(text[i].ToString(), font, color, new PointF(0, 0))
                            // 绘制干扰线
                            .DrawGridLines(10, color, imageWidth, imageHeight, imageRandom)
                            // 随机旋转
                            .Rotate(imageRandom.Next(-45, 45))
                            );
                // 将图片画到底图上
                source = source.DrawImage(img, new Point(i * textWidth, imageHeight / 7), 1);
            }
            return source;
        }

    }
}
